<template>
    <div>
        <el-row>
            <el-col align="bottom" justify="center" :span="23" :offset="1">
                <h2>配置文件比对</h2>
            </el-col>
        </el-row>

        <!-- <p>{{ fileList.length }},{{ fileList }}</p> -->
        <!-- <p>{{ selectedFiles.length }},{{ selectedFiles }}</p> -->
        

        <!-- 占位行 -->
        <el-row>
            <el-col style="min-height: 10px;"></el-col>
        </el-row>

    </div>




    <el-row>
        <el-col :span="5" :offset="1">
            <el-upload :on-change="collectFiles" :file-list="selectedFiles" class="upload-demo"
                 :multiple="true" :limit="2"
                :auto-upload="false" :before-upload="handleBeforeUpload"
                :on-remove="removeFile"
                :on-exceed="overflow"
                >
                <template #trigger>
                    <el-button type="primary">选择文件</el-button>
                </template>
                <el-button class="ml-3" type="success" @click="submitBothFiles">
                    文件对比
                </el-button>
                <el-button class="ml-3" type="info" @click="clear">
                    清空文件
                </el-button>
                <template #tip>
                    <div class="el-upload__tip text-red">
                        限制 2 个文件
                    </div>
                </template>
            </el-upload>
        </el-col>
    </el-row>

    <el-row>
        <!-- 循环渲染子组件 -->
        <el-col :span="22" :offset="1">
            <!-- loading 遮罩 -->
            <!-- <div v-loading="attr.diffLoading"> -->
            <div v-html="prettyHtml" />
            <!-- </div> -->
        </el-col>
    </el-row>





</template>


<script>
import axios from 'axios';
import DiffComponent from './DiffComponent.vue';
// import difftest from './fileDiff_test.vue';
import api from '../../api'
import * as Diff2Html from 'diff2html';
import { ElMessage } from 'element-plus';
// import { ElLoading } from 'element-plus'

export default {
    name: 'ParentComponentUp',
    computed: {
        prettyHtml() {
            return Diff2Html.html(this.diffs, {
                drawFileList: true,
                matching: 'none',
                outputFormat: 'side-by-side',
                renderNothingWhenEmpty: false, // 内容相同没有改变不输出变化
                fileContentToggle: true, // 启用文件内容折叠功能
                highlight: true, // 启用代码高亮
                synchronisedScroll: true, // 启用同步滚动
            });
        },
    },
    components: {
        DiffComponent,
        // difftest
    },
    data() {
        return {
            // fileList: [],
            selectedFiles: [], // 用于暂存选中的文件
            // num: null,
            diffs: "",
            attr: {
                // 选择框加载框
                loading: false,
                // 等待后端比对加载框
                diffLoading: false,
                percentage: null,
            },
            diffsList: [
                '--- file1.txt\n+++ file2.txt\n@@ -1,4 +1,4 @@\n 111\n\n-22\n\n-333\n\n-aaa\\n\n+222\n\n+3334\n\n+aaa',
            ],
            // 存放项目名称和分支、tag 名称
            options: [],
            // 源 tag 和目标 tag 选中后存的数据
            data: [{
                "src": [10, 'branch', 'dev'],
                "srcPath": ["pipelines/service-tp.yaml"],
                "dest": [10, 'branch', 'test'],
                "destPath": ["pipelines/service-tp.yaml"]
            }],
            // projectId: '',
            // ref: 'main',
            // tree: [],
            flattenedTree: {},
            // flattenedTreeFake: {},
            // selectedPath: '',
            props: {
                expandTrigger: 'hover',
            },
            propsPath: {
                label: "path",
                value: "path",
                expandTrigger: 'hover',
            }
        };
    },
    methods: {
        collectFiles(file, fileList) {
            // console.log("fileList.length：：：", fileList.length);
            this.selectedFiles.push(file.raw); // 收集原始文件对象
        },
        // 删除文件时
        removeFile(file, fileList) {
            // this.selectedFiles.push(file.raw); // 收集原始文件对象
            // console.log(file.raw.uid);
            this.selectedFiles.forEach((item, index) => {
                if (item.uid === file.raw.uid){
                    this.selectedFiles.splice(index, 1)

                }
            })
        },
        handleBeforeUpload(file) {
            // 阻止自动上传
            return false;
        },
        // 超出文件数量时
        overflow(files, uploadFiles){
            if (this.selectedFiles.length == 2 && files.length > 0){
                ElMessage.error("限制2个文件, 请先删除文件列表再添加!!")
            }
            if(files.length > 2){
                ElMessage.error("限制2个文件, 请重新选择!!")
            }
        },
        // submitUpload() {
        //     // console.log("type:", typeof(this.$refs.upload), "text:", this.$refs.upload);
        //     this.$refs.upload.submit();
        // },
        submitBothFiles() {
            if (this.selectedFiles.length === 2) {
                // 这里可以使用axios或其他方法发送一个包含两个文件的POST请求
                const formData = new FormData();
                this.selectedFiles.forEach((file, index) => {
                    formData.append(`file${index}`, file);
                });

                axios.post('http://localhost:8000/apis/gitlab/localfilediff/', formData)
                    .then(response => {
                        // console.log(response.data);
                        this.diffs = response.data.data
                        this.selectedFiles = []
                    })
                    .catch(error => {
                        console.error('There was an error!', error);
                    });
            } else {
                ElMessage.error("请选择两个文件进行上传和对比！！")
            }
        },
        clear(){
            this.selectedFiles = []
        },
        addSetting() {
            this.data.push({
                "src": [],
                "srcPath": "",
                "dest": "",
                "destPath": ""
            })
        },
        removeSetting(item, index) {
            console.log("item:", item);
            if (index !== -1) {
                this.data.splice(index, 1)
            }
        },
        // 获取项目分支或 tag 的目录树
        fetchTree(projectId, ref, flg, index) {
            try {
                // console.log("请求repositorytree API前：", this.getCurrentTime());
                // const response = api.repositorytree(projectId, ref);
                api.repositorytree(projectId, ref).then(res => {
                    this.flattenedTree[flg + index] = this.flattenTree(res.data);
                    // loading 加载组件
                    this.attr.percentage = 100 / this.data.length * (index + 1)
                    if (this.data.length - 1 === index) {
                        this.attr.loading = false
                    }
                })
                // console.log("请求repositorytree API后：", this.getCurrentTime());

            } catch (error) {
                console.error(error);
            }
        },
        // 格式化目录树
        flattenTree(items) {

            const result = [];
            const stack = [...items];

            while (stack.length) {
                const item = stack.pop();
                result.push(item);

                if (item.type === 'tree' && item.children) {
                    stack.push(...item.children.map(child => ({
                        ...child,
                        path: `${item.path}/${child.path}`,
                    })));
                }
            }
            return result;
        },
        // 获取项目列表和每个项目拥有的分支和 tag
        projectTrees() {
            api.projectTree().then(res => {
                // console.log(res.data);
                this.options = res.data
            })
        },
        // // 获取项目列表和每个项目拥有的分支和 tag
        // projectTrees() {
        //   api.projectTree().then(res => {
        //     // console.log(res.data);
        //     this.options = res.data
        //   })

        // },
        // 提交选中的文件进行比对
        fileDiff(data) {
            this.attr.diffLoading = true
            api.fileDiff(data).then(res => {
                this.diffs = res.data.data
                // this.diffsList = res.data.data
                this.attr.diffLoading = false
            })

        },
        handleChange(value) {
            if ([undefined, null].includes(value)) {
                console.log(`The clear value is: ${value}`);
                // ElMessage.info(`The clear value is: ${value}`)
            }
        },
        // 获取配置文件对比页面的默认数据
        getDefaultField() {
            api.defaultField().then(res => {
                if (res.data.length === 0) {
                    this.attr.loading = false
                }
                else if (res.data.length > 0) {
                    this.data = res.data;
                    this.getDefaultPath(res.data);
                }
            });
            // console.log('Received default field', res);

        },

        // 获取配置文件对比页面的 srcPath 和 destPath
        getDefaultPath(data) {
            data.forEach((item, index) => {
                this.fetchTree(item.src[0], item.src[2], 'src', index)
                this.fetchTree(item.dest[0], item.dest[2], 'dest', index)
            });

        },

        // 当前时间
        getCurrentTime() {
            //获取当前时间并打印
            var _this = this;
            let yy = new Date().getFullYear();
            let mm = new Date().getMonth() + 1;
            let dd = new Date().getDate();
            let hh = new Date().getHours();
            let mf = new Date().getMinutes() < 10 ? '0' + new Date().getMinutes() : new Date().getMinutes();
            let ss = new Date().getSeconds() < 10 ? '0' + new Date().getSeconds() : new Date().getSeconds();
            let ms = new Date().getSeconds() < 10 ? '0' + new Date().getSeconds() : new Date().getMilliseconds();
            _this.gettime = yy + '/' + mm + '/' + dd + ' ' + hh + ':' + mf + ':' + ss + ':' + ms;
            return _this.gettime
        }
    },
    mounted() {
        // 获取项目列表和每个项目拥有的分支和 tag
        // this.projectTrees()
        //获取配置文件对比页面的默认数据
        // this.getDefaultField()
    }
};
</script>